import NavBar from '@/components/NavBar';
import styles from './index.module.scss';
import Input from '@/components/Input';
import { useFormik } from 'formik';
import * as Yup from 'yup';
import { sendCodes, loginAction } from '@/store/action/user';
import { Toast } from 'antd-mobile';
import { useAppDispatch } from '@/store';
import { useState, useRef, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

/* type FormValues = {
  mobile: string,
  code: string
} */

export default function Login() {
  const [time, setTime] = useState(0);
  const timerId = useRef(-1);
  const navigate = useNavigate();

  const dispatch = useAppDispatch();
  const handleSendCodes = () => {
    if (time > 0) return;
    // 校验错误
    if (formik.errors.mobile) return Toast.show({ content: formik.errors.mobile });
    // 调用发送验证码
    dispatch(sendCodes(formik.values.mobile));
    Toast.show({ content: '获取验证码成功', duration: 1000 });
    // 开启倒计时
    setTime(60);
    timerId.current  = window.setInterval(() => {
      setTime((time) => {
        if (time === 1) {
          clearInterval(timerId.current);
        }
        return time - 1;
      });
    }, 1000);
  };

  useEffect(() => {
    return () => {
      clearInterval(timerId.current);
    }
  }, [])

  const formik = useFormik({
    initialValues: {
      mobile: '13911111111',
      code: '246810',
    },
    onSubmit: values => {
      dispatch(loginAction(values));
      Toast.show({ content: '登录成功'})
      navigate('/');
    },
    // 表单校验
    /* validate(values) {
      const errors = {} as FormValues;
      if (!/^1[3-9]\d{9}$/.test(values.mobile)) {
        errors.mobile = '手机号格式错误';
      }
      if (!/^\d{6}$/.test(values.code)) {
        errors.code = '验证码格式错误';
      }
      return errors;
    } */
    validationSchema: Yup.object().shape({
      // 手机号校验
      mobile: Yup.string()
        .required('必填项')
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
      // 验证码校验
      code: Yup.string()
        .required('必填项')
        .matches(/^\d{6}$/, '验证码号格式错误'),
    }),
  });

  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <Input
            autoFocus
            className="input"
            placeholder="请输入手机号"
            autoComplete="off"
            type="text"
            name="mobile"
            maxLength={11}
            errorMsg={formik.touched.mobile ? formik.errors.mobile : ''}
            onBlur={formik.handleBlur}
            value={formik.values.mobile}
            onChange={formik.handleChange}
          />

          {/* 短信验证码输入框 */}
          <Input
            className="input"
            placeholder="请输入验证码"
            autoComplete="off"
            type="text"
            name="code"
            maxLength={6}
            errorMsg={formik.touched.code ? formik.errors.code : ''}
            onBlur={formik.handleBlur}
            extra={
              <span onClick={() => handleSendCodes()}>
                {time === 0 ? '获取验证码' : `${time}秒后重试`}
              </span>
            }
            value={formik.values.code}
            onChange={formik.handleChange}
          />

          {/* 登录按钮 */}
          <button type="submit" className="login-btn" disabled={false}>
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
